// 主界面
;
define(function(require, exports, module) {
	'use strict';
	var util = require("util");
	var base = require("base");
	var leftMenu = require("../leftMenu/leftMenu");
	var topMenu = require("../topMenu/topMenu");
	var footer = require("../footer/footer_main");
	var router = require("../hash/pageRouter");
	var dialog = require("dialog");
	var databind = require("databind");
	var css_dialog = require("css_dialog");
	var validate = require("validate");
	var tools = require("tools");
	var html_receivables_detail = require("./html_receivables_detail.html");
	var html_loan_detail = require("./html_loan_detail.html");
	var html_expense_detail = require("./html_expense_detail.html");
	var html_verifyRecord = require("./html_verifyRecord.html");
	var financeId;
	var type;
	var storage = window.localStorage;
	var source;
	var verifiCancelState;
	var pageIndex = 1,
		pageSize = 10,
		totalPageCount = 1,
		totalRecordCount = 0; //分页初始化
	var oData = {
		pageIndex: pageIndex,
		pageSize: pageSize,
		totalPageCount: totalPageCount,
		totalRecordCount: totalRecordCount,
		statementBeginDate: "",
		statementEndDate: "",
		statementNumber: "",
		receiptName: "",
		minSourceAmount: "",
		maxSourceAmount: "",
		financeNumber: ""
	};
	var init = function() {
		oData = tools.GetRequest(oData, null);
		if (oData != null) {
			$(".statementBeginDate").val(oData.statementBeginDate);
			$(".statementEndDate").val(oData.statementEndDate);
			$(".statementNumber").val(oData.statementNumber);
			$(".receiptName").val(oData.receiptName);
			$(".minSourceAmount").val(oData.minSourceAmount);
			$(".maxSourceAmount").val(oData.maxSourceAmount);
			$(".financeNumber").val(oData.financeNumber);
//			$(".statementSource").val(oData.statementSource);
			$(".wrapper select[name=productType]").val(oData.productType);
			$(".wrapper select[name=verifiCancelState]").val(oData.verifiCancelState);
		}
		type = base.getUrlParam("type");
		financeId = base.getUrlParam("financeId");
		source = eval ("(" + base.getUrlParam("source") + ")");
		verifiCancelState = base.getUrlParam("verifiCancelState");
		oData.verifiCancelState = verifiCancelState;
		footer.init();
		$("#footer").removeClass("none");
		leftMenu.init(5);
		topMenu.init(1);
		router.init();
		$(".table-section").removeClass("none");
		$(".footer").removeClass("none");
		if (type == "capital") {
			oData.financeId = financeId;
			oData.verifiCancelState = verifiCancelState;
			oData.statementSource = source;
		}
		
		tableInit();
		tools.loadList("inquireDisbursementMoneyStatementPageList.json", $("#disbursementManageBody"), $("#disbursementManageTpl"), oData, function() {
			$("#disbursementManageTable").trigger("update");
			
			$("#disbursementManageTable .verifyRecord").unbind("click").click(function(){
				var $this = $(this);
				var ii = layer.open({
	        	  area: ['1000px', '600px'], //宽高
				  title: "核销记录",
				  type: 1,
				  skin: 'layui-layer-demo', //样式类名
				  closeBtn: 1, //不显示关闭按钮
				  anim: 2,
				  shadeClose: true, //开启遮罩开启
				  content: html_verifyRecord,
				  btn: ['确定'],
				  yes: function(){
				  	layer.close(ii);
				  }
				});
				
				var o = {
					pageIndex: pageIndex,
					pageSize: pageSize,
					totalPageCount: totalPageCount,
					totalRecordCount: totalRecordCount,
					moneyStatementId: $this.parents("tr").attr("moneyStatementId"),
					billType: 2
				};
				
				tools.loadList("inquireBillReceivablePageList.json", $(".html_verifyRecord table"), $(".html_verifyRecord script"), o, function() {
					$(".html_verifyRecord .detail").unbind("click").click(function() {
						storage.setItem("type", "detail");
						window.open("../moneyStatementManage/verifyDisbursement.html?type=detail&billReceivableId=" + $(this).parents("tr").attr("billReceivableId"));
					});
				}, $(".html_verifyRecord .pagerCon"));
			});
		});
		$("#disbursementManageTable").trigger("update");
		$(".disbursementManage").parent().parent().parent().addClass("leftMenu-open");
		$(".disbursementManage").parent().addClass("leftMenu-active");
		initEvent();
	};
	var initEvent = function() {
		//若未登录，则返回登陆页面
		if (base.getData("sid") == null || base.getData("sid") == "" || base.getData("sid") == undefined) {
			location.href = "../login/login.html";
		};
		
		$("#leftMenu9").on("click", ".claimManage", function() {
			router.route("claimManage/claimManage.html");
		});

		$("#leftMenu9").on("click", ".insurance1", function() {
			location.href = "../insuranceManage/insuranceManage.html";
		});

		$("#leftMenu9").on("click", ".insurance2", function() {
			location.href = "../insuranceManage/insuranceManage.html";
		});

		$("#leftMenu9").on("click", ".insurance3", function() {
			location.href = "../insuranceManage/insuranceManage.html";
		});

		$("#leftMenu9").on("click", ".insurance4", function() {
			location.href = "../insuranceManage/insuranceManage.html";
		});
		
		//已完成融资
		$(".endFinanceList").unbind("click").click(function() {
			location.href = "../financing/endFinanceList.html";
		});
		//收货通知查询
		$(".recieveNoticeList").unbind("click").click(function() {
			location.href = "../financing/recieveNoticeList.html";
		});
		//放货查询
		$(".deliveryNoticeList").unbind("click").click(function() {
			location.href = "../financing/deliveryNoticeList.html";
		});
		//放款单查询
		$(".loanNoticeList").unbind("click").click(function() {
			location.href = "../financing/loanNoticeList.html";
		});

		$("#main").on("click", "#disbursementSearch", function() {
			pageIndex = 1;
			pageSize = 10;
			totalPageCount = 1;
			totalRecordCount = 0; //分页初始化			
			oData = {
				pageIndex: pageIndex,
				pageSize: pageSize,
				totalPageCount: totalPageCount,
				totalRecordCount: totalRecordCount,
				statementBeginDate: $(".statementBeginDate").val(),
				statementEndDate: $(".statementEndDate").val(),
				statementNumber: $(".statementNumber").val(),
				receiptName: $(".receiptName").val(),
				minSourceAmount: $(".minSourceAmount").val(),
				maxSourceAmount: $(".maxSourceAmount").val(),
				financeNumber: $(".financeNumber").val(),
				productType: $(".wrapper select[name=productType]").val(),
				verifiCancelState: $(".wrapper select[name=verifiCancelState]").val()
			};
			if (type == "capital") {
				oData.financeId = financeId;
				oData.verifiCancelState = verifiCancelState;
				oData.statementSource = source;
			}
			tools.loadList("inquireDisbursementMoneyStatementPageList.json", $("#disbursementManageBody"), $("#disbursementManageTpl"), oData, function() {
				$("#disbursementManageTable").trigger("update");
				$(".detail").unbind("click").click(function() {
					//router.route("insuranceManage/insuranceDetail.html?insuranceId=" + $(this).parents("tr").attr("insuranceId") + "&financeId=" + $(this).parents("tr").attr("financeId"));
				});
			
				$("#disbursementManageTable .verifyRecord").unbind("click").click(function(){
					var $this = $(this);
					var ii = layer.open({
		        	  area: ['1000px', '600px'], //宽高
					  title: "核销记录",
					  type: 1,
					  skin: 'layui-layer-demo', //样式类名
					  closeBtn: 1, //不显示关闭按钮
					  anim: 2,
					  shadeClose: true, //开启遮罩开启
					  content: html_verifyRecord,
					  btn: ['确定'],
					  yes: function(){
					  	layer.close(ii);
					  }
					});
					
					var o = {
						pageIndex: pageIndex,
						pageSize: pageSize,
						totalPageCount: totalPageCount,
						totalRecordCount: totalRecordCount,
						moneyStatementId: $this.parents("tr").attr("moneyStatementId"),
						billType: 2
					};
					
					tools.loadList("inquireBillReceivablePageList.json", $(".html_verifyRecord table"), $(".html_verifyRecord script"), o, function() {
						$(".html_verifyRecord .detail").unbind("click").click(function() {
							storage.setItem("type", "detail");
							window.open("../moneyStatementManage/verifyDisbursement.html?type=detail&billReceivableId=" + $(this).parents("tr").attr("billReceivableId"));
						});
					}, $(".html_verifyRecord .pagerCon"));
				});
			
			});
		});
		
		$("#main").on("click", ".forceVerify", function(){
			var $this = $(this);
			dialog.showConfirmDialog("关闭流水", "是否关闭该条流水？", function(){
				forceVerifiDisbursementMoneyMoneyStatement($this.parents("tr").attr("moneystatementId"));
			});
		});
		
		$("#main").on("click", ".repulse_1", function(){
			var $this = $(this);
			dialog.showConfirmDialog("打回", "是否确定打回？", function(){
			  callbackMoneyStatement($this.parents("tr").attr("moneystatementId"));
			});
		});
		
		$("#main").on("click", ".verify", function(){
			var $this = $(this);
			var str = $this.parents("tr").next().prop("outerHTML");
//			location.href = "../moneyStatementManage/verifyDisbursement.html?type=singleVerify&str=" +encodeURI(encodeURI(str)) + "&receiptId=" + $this.parents("tr").find(".receiptName").attr("receiptId") + "&receiptName=" + encodeURI(encodeURI($this.parents("tr").find(".receiptName").html()));

			storage.setItem("type", "singleVerify");
			storage.setItem("str", encodeURI(encodeURI(str)));
			storage.setItem("receiptId", $this.parents("tr").find(".receiptName").attr("receiptId"));
			storage.setItem("receiptName", encodeURI(encodeURI($this.parents("tr").find(".receiptName").html())));
			
			location.href = "../moneyStatementManage/verifyDisbursement.html?1=1" + tools.urlEncode(oData, null);
		});

		$("#main").on("click", ".detail", function() {
			var statementSourceId = $(this).parents("tr").attr("statementSourceId");
			var statementSource = $(this).parents("tr").attr("statementSource");
			switch (statementSource) {
				case "RECEIVABLES":
					$("#popdialog").html(html_receivables_detail);
					dialog.showDialog($("#receivable_detail_dialog"));
					databind.fillInput($("#receivable_detail_dialog"), {
						action: "inquireReceivablesDetail.json?receivablesId=" + statementSourceId
					});
					databind.disableInput($("#receivable_detail_dialog"));
					$(".sure_yes").unbind("click").click(function() {
						dialog.hideDialog($("#receivable_detail_dialog"));
					});

					$(".sure_no").unbind("click").click(function() {
						router.route("financing/receivableNoticeDetail.html?receivablesId=" + statementSourceId);
						dialog.hideDialog($("#receivable_detail_dialog"));
					});
					break;
				case "ABNORMAL_EXPENSE":
					$("#popdialog").html(html_expense_detail);
					dialog.showDialog($("#exception_detail_dialog"));
					tools.inquireCommonSelectorList(9, $(".expenseType"));
					databind.fillInput($("#exception_detail_dialog"), {
						action: "inquireAbnormalExpenseDetail.json?abnormalExpenseId=" + statementSourceId
					});
					databind.disableInput($("#exception_detail_dialog"));
					$(".sure_yes").unbind("click").click(function() {
						dialog.hideDialog($("#exception_detail_dialog"));
					});
					$(".sure_no").unbind("click").click(function() {
						var abnormalId = $("#abnormalId").val();
						dialog.hideDialog($("#exception_detail_dialog"));
						storage.setItem("abnormalId", abnormalId);
						location.href="../exception/exceptionManage.html#exception/exceptionDetailInfo";
					});
					break;
				case "LOAN_NOTICE":
					$("#popdialog").html(html_loan_detail);
					dialog.showDialog($("#loan_detail_dialog"));
					databind.fillInput($("#loan_detail_dialog"), {
						action: "inquireLoanNoticeDetail.json?loanNoticeId=" + statementSourceId
					});
					databind.disableInput($("#loan_detail_dialog"));
					$(".sure_yes").unbind("click").click(function() {
						dialog.hideDialog($("#loan_detail_dialog"));
					});

					$(".sure_no").unbind("click").click(function() {
						router.route("financing/loanNotice.html?loanNoticeId=" + statementSourceId);
						dialog.hideDialog($("#loan_detail_dialog"));
					});
					break;
				case "INSURANCE":
					router.route("insuranceManage/insuranceDetail.html?insuranceId=" + statementSourceId);
					break;
				case "FINANCE_AUDIT":
					router.route("main/financeApproveDetail.html.html?financeAuditId=" + statementSourceId);
					break;
				case "BAIL_RETURN":
					router.route("financing/financingDetailInfo.html?financeId=" + statementSourceId);	
					break;
				default:
					break;
			}
		});
	};
	
	//强制核销-付款
	var forceVerifiDisbursementMoneyMoneyStatement = function(moneyStatementId) {
		base.fnAjax({
			action: "forceVerifiDisbursementMoneyMoneyStatement.json", //接口名称
			oData: {
				moneyStatementId: moneyStatementId
			}, //传递参数
			fnSuccess: function(data) { //成功回调
				if (data.status == 200) {
					base.alert(1, "核销成功！");
					location.href = "../moneyStatementManage/disbursementManage.html";
				}
			}
		});
	};
	
	//打回确认
	var callbackMoneyStatement = function(moneyStatementId) {
		base.fnAjax({
			action: "callbackMoneyStatement.json", //接口名称
			oData: {
				moneyStatementId: moneyStatementId 
			}, //传递参数
			fnSuccess: function(data) { //成功回调
				if (data.status == 200) {
					layer.msg("打回成功！");
					layer.closeAll();
					location.href = "../moneyStatementManage/disbursementManage.html";
				}
			}
		});
	};
	
	//tablesorter初始化
	var tableInit = function() {
		$("#disbursementManageTable").tablesorter({
		    widthFixed: false,
			theme: 'blue',
			showProcessing: false,
			tabIndex: true,
			sortMultiSortKey: "shiftKey",
		    sortResetKey: 'ctrlKey',
			ignoreCase: true,
			sortForce: null,
			resort:false,
			headers:{
				 0: {sorter: false},
				 1: {sorter: false},
      			 2: {sorter: false},
      			 3: {sorter: false},
      			 4: {sorter: false},
      			 5: {sorter: false},
      			 6: {sorter: false},
      			 7: {sorter: false},
      			 8: {sorter: false},
      			 9: {sorter: false},
      			 10: {sorter: false}
				},
			headerTemplate : '{content} {icon}',
			widgets: [ 'zebra', 'scroller' ],
			widgetOptions : {
		      scroller_height : 420,
		      // scroll tbody to top after sorting
		      scroller_upAfterSort: true,
		      // pop table header into view while scrolling up the page
		      scroller_jumpToHeader: true,
		      // In tablesorter v2.19.0 the scroll bar width is auto-detected
		      // add a value here to override the auto-detected setting
		      scroller_barWidth : null
		      // scroll_idPrefix was removed in v2.18.0
		      // scroller_idPrefix : 's_'
		    }
		});
		  
		//事件
	  	$("#disbursementManageTable").bind("sortEnd",function(event) {
			var table = event.target;
			var columnSort       =  table.config.sortList[0][0];          									 //第几列排序，序号
			var columnSortName   =  $(table.config.headerList[table.config.sortList[0][0]]).text();          //第几列排序，名称
			var columnSortType   =  table.config.sortList[0][1];    	  									 //0:升序，1：降序
			//测试代码2：排序
		});
	};

	return {
		init: init
	};
});